package palmtop.com.palmtop.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.widget.Button;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import palmtop.com.palmtop.R;
import palmtop.com.palmtop.util.Config;

public class SelectPositionActivity extends BaseActivity implements GeocodeSearch.OnGeocodeSearchListener {

    @BindView(R.id.mapViews)
    MapView mapViews;

    AMap aMap = null;
    @BindView(R.id.confirm)
    Button confirm;
    @BindView(R.id.cancel)
    Button cancel;
    private String address = "";
    private Double latitude;
    private Double longitude;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    boolean flag = false;
    Context context;
    Marker marker;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_position, Config.toptitle, 1);
        ButterKnife.bind(this);
        mapViews.onCreate(savedInstanceState);
        context = this;
        aMap = mapViews.getMap();
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                latLng.toString();
                //Log.e("latlon",latLng.latitude+"    "+latLng.longitude);
                getAddress(latLng.latitude,latLng.longitude);
                latitude = latLng.latitude;
                longitude = latLng.longitude;
                marker.remove();
                marker = aMap.addMarker(new MarkerOptions().position(latLng).title(""));
                //marker.setDraggable(true);
                marker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(), R.mipmap.online)));

            }
        });
        //aMap.setOnMarkerDragListener(markerDragListener);

        getGpsInfo();

    }

    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    if (flag == false) {
                        LatLng ln = new LatLng(amapLocation.getLatitude(), Double.valueOf(amapLocation.getLongitude()));
                        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(ln, 16, 0, 0));
                        aMap.moveCamera(cameraUpdate);
                        marker = aMap.addMarker(new MarkerOptions().position(ln).title(""));
                        //marker.setDraggable(true);
                        marker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                .decodeResource(getResources(), R.mipmap.online)));
//                        marker.setMarkerOptions();
                        latitude = ln.latitude;
                        longitude = ln.longitude;
                        getAddress(ln.latitude, ln.longitude);

                        flag = true;
                    }

                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    private void getGpsInfo() {
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setOnceLocation(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    private void getAddress(double lat, double lon) {
        GeocodeSearch geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(lat, lon), 200, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
    }

    @OnClick(R.id.confirm)
    public void onConfirmClicked() {
        Intent intent = new Intent();
        //把返回数据存入Intent
        intent.putExtra("latitude", latitude);
        intent.putExtra("longitude", longitude);
        intent.putExtra("address", address);
        //设置返回数据
        SelectPositionActivity.this.setResult(RESULT_OK, intent);
        //关闭Activity
        SelectPositionActivity.this.finish();
    }

    @OnClick(R.id.cancel)
    public void onCancelClicked() {
        Intent intent = new Intent();
        //把返回数据存入Intent
        intent.putExtra("latitude", "");
        intent.putExtra("longitude", "");
        intent.putExtra("address", "");
        //设置返回数据
        SelectPositionActivity.this.setResult(RESULT_OK, intent);
        //关闭Activity
        SelectPositionActivity.this.finish();
    }


    //marker拖拽监听事件
    AMap.OnMarkerDragListener markerDragListener = new AMap.OnMarkerDragListener() {
        @Override
        public void onMarkerDragStart(final Marker marker) {
        }

        @Override
        public void onMarkerDrag(final Marker marker) {
        }

        @Override
        public void onMarkerDragEnd(final Marker marker) {
//            AlertDialog.Builder b = new AlertDialog.Builder(context);
//            b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialogInterface, int i) {
                    LatLng ln = marker.getPosition();
                    latitude = ln.latitude;
                    longitude = ln.longitude;
                    getAddress(ln.latitude, ln.longitude);
//                }
//            });

           /* b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });
            b.setMessage("确认定位到此处?");
            b.setTitle("提示");
            b.show();*/

        }

    };


    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        if (i == 1000) {
            address = regeocodeResult.getRegeocodeAddress().getFormatAddress();
            /*Intent intent = new Intent();
            //把返回数据存入Intent
            intent.putExtra("latitude", latitude);
            intent.putExtra("longitude", longitude);
            intent.putExtra("address", address);
            //设置返回数据
            SelectPositionActivity.this.setResult(RESULT_OK, intent);
            //关闭Activity
            SelectPositionActivity.this.finish();*/

        }

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapViews.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapViews.onResume();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapViews.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapViews.onDestroy();
    }



}
